package munci.read;

import java.io.StringReader;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;


public class Tokens {

	private final List<Token> contents = new LinkedList<Token>();

	public static Tokens create(Token... toks) {
		Tokens list = new Tokens();
		for (Token tok : toks) {
			list.add(tok);
		}
		return list;
	}
	
	public Tokens add(Token tok) {
		contents.add(tok);
		return this;
	}
	
	public Tokens add(String image) {
		return add(Token.get(image));
	}
	
	public Tokens lex(String text) {
		ReaderTokenizer toker = new ReaderTokenizer(new StringReader(text), "input");
		for (Token tok = toker.token(); tok != null; toker.nextToken()) {
			add(tok);
		}
		return this;
	}
	
	public Tokens addAll(Tokens toks) {
		contents.addAll(toks.asList());
		return this;
	}
	
	public boolean startsWith(String image) {
		return contents.size() > 0 && contents.get(0).image().equals(image);
	}
	
	public boolean endsWith(String image) {
		return contents.size() > 0 && contents.get(contents.size() - 1).image().equals(image);
	}
	
	public List<Token> asList() {
		return contents;
	}
	
	public Tokenizer tokens() {
		final Iterator<Token> toks = contents.iterator();
		return new Tokenizer() {
			boolean next = true;
			Token tok = null;
			
			public void nextToken() {
				if (next) throw new RuntimeException("Current token has not been consumed");
				next = true;
			}
			public Token token() {
				if (next) {
					tok = toks.hasNext()? toks.next() : null;
					next = false;
				}
				return tok;
			}
		};
	}
	
	@Override public String toString() {
		StringBuilder str = new StringBuilder(); //.append('[');
		char last = '/';
		for (Token tok : contents) {
			char c = tok.image().charAt(0);
			if (Character.isJavaIdentifierPart(last) && Character.isJavaIdentifierPart(c))
				str.append(' ');
			str.append(tok.image());
			last = c;
		}
		//str.append(']')
		return str.toString();
	}
}
